#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>

const int defaultbacklog = 10;

class Sock
{
public:
    Sock()
    {}
    ~Sock()
    {}

    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd < 0)
        {
            perror("create socket fail\n");
            exit(1);
        }
    }

    void Bind(uint16_t port = 0, const std::string ip = "0.0.0.0")
    {
        sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &server.sin_addr);
        socklen_t len = sizeof(server);

        int n = bind(_sockfd, (sockaddr*)&server, len);
        if(n < 0)
        {
            perror("bind socket fail\n");
            exit(1);
        }
        std::cout << "bind success" << std::endl;
    }

    void Listen()
    {
        int n = listen(_sockfd, defaultbacklog);
        if(n < 0)
        {
            perror("listen fail\n");
            exit(1);
        }
    }

    // port 和 ip 是输出参数，返回客户端port 和客户端ip
    int Accept(uint16_t& port, std::string& ip)
    {
        sockaddr_in client;
        socklen_t len;
        int newfd = accept(_sockfd, (sockaddr*)&client, &len);//拿到客户的fd 
        char ipstr[30] = {0};
        inet_ntop(AF_INET, &client.sin_addr, ipstr, sizeof(ipstr)); 
        
        port = ntohs(client.sin_port);;
        ip = std::string(ipstr);

        return newfd;
    }

    int Connect(uint16_t port = 0, const std::string ip = "0.0.0.0")
    {
        sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &server.sin_addr);
        socklen_t len = sizeof(server);
        connect(_sockfd, (sockaddr*)&server, len);

        return 0;
    }

    void Close()
    {
        close(_sockfd);
    }

    int getsockfd()
    {
        return _sockfd;
    }
private:
    int _sockfd;
};